package org.raymond.iworks.core.listener;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.raymond.iworks.commons.constants.CommonConstants;
import org.raymond.iworks.commons.utils.NetworkUtil;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Properties;

/**
 * @author raymond
 * @version V1.0
 * @Description: TODO
 */
@Slf4j
@Component
public class AppPropertiesPreparedListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {

    @Override
    public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
        int port = 0;
        String serverPort = event.getEnvironment().getProperty("SERVER_PORT");
        log.info("SERVER_PORT: {}", serverPort);
        if(StringUtils.isNotBlank(serverPort)){
            port = Integer.parseInt(serverPort);
        }else{
            port = loadPortFromProperties();
        }
        String portStr = String.valueOf(port);
        System.setProperty("server.port", portStr);
        System.setProperty("spring.cloud.consul.discovery.port", portStr);
        log.info("set port:{}", port);
    }

    private int loadPortFromProperties(){
        Properties baseProperties = null;
        int start = 20000;
        int end = 40000;
        int port = 0;
        try {
            baseProperties = PropertiesLoaderUtils.loadAllProperties("application.properties");
            String portStr = baseProperties.getProperty("server.port");
            if(StringUtils.isBlank(portStr)) {
                start = Integer.parseInt(baseProperties.getProperty("icloud.port.start", "20000"));
                end = Integer.parseInt(baseProperties.getProperty("icloud.port.end", "40000"));
            }else if(CommonConstants.DIGITAL.matcher(portStr).matches()){
                port = Integer.parseInt(portStr);
            }else if(portStr.startsWith("${") && portStr.endsWith("}")){
                String portKey = portStr.substring(2, portStr.length()-1);
                String portValue = baseProperties.getProperty(portKey);
                port = Integer.parseInt(portValue);
            }
        } catch(NumberFormatException | IOException e){
            log.error(e.getMessage());
            port = 0;
        }

        try {
            if(port<=0) {
                port = NetworkUtil.randomPort(start, end);
            }
        } catch (NumberFormatException | IOException e){
            log.error(e.getMessage());
        }
        return port;
    }
}
